/* 配额调整-调剂
 * @Author: Setsuna
 * @Email: 601890383@qq.com
 * @FilePath: \src\pages\QuotaManage\QuotaAdjust\component\AdjustForm.tsx
 * @Date: 2021-08-30 09:31:11
 * @LastEditTime: 2021-09-07 15:08:52
 */
import React, { createRef } from 'react'
import { http, IUdFormItem, UdForm, validators } from '@/lib'
import UdUploader from '@/components/UdUploader/Uploader'
import { Input, Select, InputNumber, message } from 'antd'
import { WrappedFormUtils } from 'antd/lib/form/Form'
import quotaApis from '@/apis/AboutQuota'
import todoApi from '@/apis/TodoList/index'
import moment from 'moment'
import QuotaApprove from '@/components/getQuotaApprove'
import { differenceBy } from 'lodash'
import './approve.scss'
const { TextArea } = Input
const { Option } = Select
interface IProps {
  id?: number
  record: any
  handQuery?: any
  planType?: number
}
interface IState {
  record: any
  workFlowList: any[]
  checkPerson: any[]
  isApprove?: any
}
export default class AdjustForm extends React.Component<IProps, IState> {
  private labelCol: any = { span: 4 }
  private form: WrappedFormUtils
  private PLAN_TYPE_ENUM: any = {
    0: '计划内',
    1: '计划外',
  }
  public cRef = createRef<any>()

  state = {
    record: { modifyType: '' },
    workFlowList: [],
    checkPerson: [],
    isApprove: {
      quotaAdjustAdjust: false, 
    },
  }

  componentDidMount() {
    let params={ brandCode: this.props.record['brandCode'], prodBarcode: this.props.record['prodBarcode'] };
    http.get(todoApi.getProcessKeyFlow, { params }).then(res => {
      this.setState({
        isApprove:res.data
      })
    })
    let record = { ...this.props.record }
    let { planType } = this.props
    record.term = `${record.stageBeginTime}-${record.stageEndTime}`
    record.modifyType = 'ADJUST'
    record.planTypeText = this.PLAN_TYPE_ENUM[planType]
    record.id = this.props.id
    this.setState({ record }, () => {
      this.getWorkFlow()
    })
  }

  private onOk = e => {
    this.form.validateFields((err, values) => {
      if (!err) {
        if (this.state.isApprove?.quotaAdjustAdjust&&this.state.checkPerson.length === 0) {
          message.warn('请选择审批人')
          return false
        }
        e.drawerBtnLoading()
        let params = { ...this.props.record, ...values }
        params.id = this.props.id
        delete params.planTypeText
        params.stageBeginTime = moment(params.stageBeginTime).format('YYYY-MM-DD HH:mm:ss')
        params.stageEndTime = moment(params.stageEndTime).format('YYYY-MM-DD HH:mm:ss')
        if(this.state.checkPerson.length>0){
          params['workflowReqVos'] = {
            name: 'candidateUsers',
            userId: [this.state.checkPerson[0].id],
          }
        }
        http
          .post(quotaApis.saveOrUpdateDispatchHistory, params)
          .then(() => {
            message.success('操作成功')
            e.close()
          })
          .catch(() => {
            e.drawerBtnLoadingHide()
          })
      } else {
        console.log(err)
      }
    })
  }

  //获取审批角色
  private getWorkFlow = () => {
    http.get(todoApi.getAdjustNextApprove, { params: { brandCode: this.state.record['brandCode'], modifyType: this.state.record.modifyType || '' } }).then(res => {
      const { data } = res
      this.setState({ workFlowList: data })
    })
  }

  //选择审批人
  private handShowQuotaApprove(index) {
    this.cRef.current.handelCeck(index)
  }

  private handGetPerson(value) {
    this.setState({ checkPerson: value })
  }

  render() {
    let { planType } = this.props
    let items: IUdFormItem[] = [
      { label: '品牌公司', id: 'brandName', render: () => <Input readOnly /> },
      { label: '配额品项', id: 'prodBarname', render: () => <Input readOnly /> },
      { label: '考核年度', id: 'stageYear', render: () => <Input readOnly /> },
      { label: '考核阶段', id: 'stageName', render: () => <Input readOnly /> },
      { label: '配额有效期', id: 'term', render: () => <Input readOnly /> },
      { label: '客户名称', id: 'dealerName', render: () => <Input readOnly /> },
      { label: '年度剩余配额', id: 'residualQuotaYearSum', render: () => <Input readOnly /> },
      { label: '年度剩余配额', id: 'residualQuotaYearSumWay', render: () => <Input readOnly /> },
      { label: '考核阶段剩余配额', id: 'residualQuota', render: () => <Input readOnly /> },
      { label: '考核阶段剩余配额', id: 'residualQuotaWay', render: () => <Input readOnly /> },
      { label: '计划类型', id: 'planTypeText', render: () => <Input readOnly /> },
      {
        label: '调整类型',
        id: 'modifyType',
        render: () => (
          <Select disabled>
            <Option value="UP">调增</Option>
            <Option value="DOWN">调减</Option>
            <Option value="ADJUST">调剂</Option>
            <Option value="READJUST">客户间调整</Option>
          </Select>
        ),
      },
      {
        label: '调整数量',
        id: 'modifyQuota',
        rules: [validators.required],
        render: (
          <InputNumber
            min={1}
            max={
              planType === 0 ? this.state.record['residualQuotaYearSum'] : this.state.record['residualQuotaYearSumWay']
            }
            precision={0}
            style={{ width: '100%' }}
            readOnly={
              !(planType === 0
                ? this.state.record['residualQuotaYearSum']
                : this.state.record['residualQuotaYearSumWay'])
            }
          />
        ),
      },
      { label: '备注信息', id: 'remark',rules: [validators.required], render: <TextArea rows={3} maxLength={200} /> },
      {
        label: '凭证附件',
        id: 'quotaApplyDetailFileRespVoList',
        render: <UdUploader form={this.form} extra="支持扩展名：.jpg .png .xls .doc" />,
      },
    ]
    const filterFiles: object = {
      1: [{ id: 'residualQuotaYearSum' }, { id: 'residualQuota' }],
      0: [{ id: 'residualQuotaYearSumWay' }, { id: 'residualQuotaWay' }],
    }

    items = differenceBy(items, filterFiles[planType], 'id') as IUdFormItem[]
    return (
      <>
        <UdForm
          labelCol={this.labelCol}
          getForm={form => (this.form = form)}
          items={items}
          values={this.state.record}
        />
        {this.state.isApprove?.quotaAdjustAdjust&&<div className="approve-wrap">
          <div className="node-name-wrap">
            <div className="approve-title">节点名称：</div>
            <span className="circle-point"></span>
            <div>{this.state.workFlowList[0]?.nodeName || '暂无'}</div>
          </div>
          <div className="person-name-wrap">
            <div className="approve-title">审批人:</div>
            <div
              className={this.state.checkPerson[0]?.realName ? 'add-plus-name' : 'add-plus'}
              onClick={() => {
                this.handShowQuotaApprove(0)
              }}
            >
              {this.state.checkPerson[0]?.realName || '+'}
            </div>
          </div>
        </div>}
        <QuotaApprove
          handCilck={this.handGetPerson.bind(this)}
          cRef={this.cRef}
          ids={this.state.workFlowList[0]?.roleIds}
        />
      </>
    )
  }
}
